import mitt from "mitt";
import type { Emitter, Handler } from "mitt";
import { getCurrentScope, onUnmounted } from "vue";

const mittInstance: Emitter<any> = mitt();

export const useMitt = {
  on: (event: string, handler: Handler<any>) => {
    mittInstance.on(event, handler);
    if (getCurrentScope()) {
      onUnmounted(() => {
        mittInstance.off(event, handler);
      });
    }
  },
  emit: (event: string, data?: any) => {
    mittInstance.emit(event, data);
  },
  off: (event: string, handler: Handler<any>) => {
    mittInstance.off(event, handler);
  },
};
